package chapter3.pp3_8;


import chapter4.pp4_2.StackADT;

import java.util.Arrays;
import java.util.EmptyStackException;

public class ArrayStack<T> implements StackADT<T> {
    private final int DEFAULT_CAPACITY = 100;
    private int top;
    private T[] stack;
    public ArrayStack(){
        top = 0;
        stack = (T[]) (new Object[DEFAULT_CAPACITY]);
    }

//    public ArrayStack(int initialCapacity){
//        top = 0;
//        stack = (T[]) (new Object[initialCapacity]);
//    }
    @Override
    public void  push(T element){
        if(size()==stack.length)
            expandCapacity();
        stack[top] = element;
        top++;
    }
    private void expandCapacity(){
        stack= Arrays.copyOf(stack,stack.length*2);
    }
    @Override
    public int size(){
        int b=0;
        for(int a = 0; stack[a] != null;a++)
        {
           b++;
        }

        return b;
    }
    @Override
    public T pop() throws EmptyCollectionException
    {
        if (isEmpty())
            throw new EmptyCollectionException("Stack");
        top--;
        T result = stack[top];
        stack[top] = null;

        return result;
    }
    @Override
    public T peek() throws EmptyStackException
    {
        if (isEmpty())
            throw new EmptyCollectionException("Stack");

        return stack[top-1];
    }
@Override
public boolean isEmpty(){
        boolean p ;
        if (stack[0]!=null){
            p=false;
        }
        else
        {
            p=true;
        }
    return p;
}

@Override
public String toString(){
        String result = "";
        for(int a = 0; a<size();a++){
            result += String.valueOf(stack[a] +" ");
        }
    return result;
}

}
